package com.yhy.gateway.config;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.nimbusds.jose.JWSObject;
import com.yhy.common.core.exception.BizException;
import com.yhy.common.core.result.Result;
import com.yhy.common.core.result.ResultEnum;
import com.yhy.common.redis.utils.RedisUtil;
import com.yhy.common.security.constant.SecurityConstants;
import com.yhy.gateway.utils.ResponseUtils;
import com.yomahub.tlog.context.TLogContext;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 安全拦截全局过滤器,优先级低
 * {@link AuthorizationManager#check(reactor.core.publisher.Mono, org.springframework.security.web.server.authorization.AuthorizationContext)} 鉴权之后执行
 */
@Slf4j
@Component
public class SecurityGlobalFilter implements GlobalFilter {

    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 错误的JWT不做解析处理
        String token = request.getHeaders().getFirst(SecurityConstants.AUTHORIZATION_KEY);
        if (StrUtil.isBlank(token) || !StrUtil.startWithIgnoreCase(token, SecurityConstants.JWT_PREFIX)) {
            return chain.filter(exchange);
        }
        // 从token中获取到用户信息并set到header中
        token = StrUtil.replaceIgnoreCase(request.getHeaders().getFirst(SecurityConstants.AUTHORIZATION_KEY)
                , SecurityConstants.JWT_PREFIX, Strings.EMPTY);
        if (StrUtil.isBlank(token)) {
            return chain.filter(exchange);
        }
        String payload = StrUtil.toString(JWSObject.parse(token).getPayload());
        JSONObject jsonObject = JSONUtil.parseObj(payload);

        String jti = jsonObject.getStr(SecurityConstants.JWT_JTI);
        Integer exp = jsonObject.getInt(SecurityConstants.JWT_EXP);
        String user = jsonObject.getStr(SecurityConstants.DETAILS_USER);
        request = exchange.getRequest().mutate()
                .header(SecurityConstants.JWT_JTI, jti)
                .header(SecurityConstants.JWT_EXP, String.valueOf(exp))
                .header(SecurityConstants.JWT_PAYLOAD_KEY, payload)
                .header(SecurityConstants.DETAILS_USER, Base64.encode(user))
                .build();
        exchange = exchange.mutate().request(request).build();
        return chain.filter(exchange);
    }

}
